//
//  SetAlertViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/22.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "SetAlertViewController.h"
#import "AppDelegate.h"
#import "SelectRateViewController.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "SetTextViewController.h"
#import "RecordViewController.h"
#import "VoiceConverter.h"
@import AVFoundation;
@import AudioToolbox;
@interface SetAlertViewController ()
@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;
@property (nonatomic,weak) AppDelegate *mydelegate;

@property(nonatomic,assign) BOOL isAdd;
@property(nonatomic,assign) BOOL is_play;
@property(nonatomic,assign) BOOL isUnderRecord;
@property(nonatomic,strong) RecordViewController *recordView;
@property(nonatomic,assign) BOOL isCancle;
@property(nonatomic,strong)  UIWindow *keyWindow;
@property(nonatomic,strong)  UIWindow *alertView;
@property(nonatomic,strong) NSTimer *timer;
@property(nonatomic,strong) NSTimer *Newtimer;
@property(nonatomic,strong) NSString *recordPath;
@property(nonatomic,strong) AVAudioPlayer *player;
@property(nonatomic,assign) CGPoint previous;
@property(nonatomic,assign) CGPoint current;
@property(nonatomic,assign) int alertType;



@end

@implementation SetAlertViewController
@synthesize navRightButton;
@synthesize navLeftButton;
@synthesize dataPicker;
@synthesize titleView;
@synthesize titleLabel;
@synthesize rateView;
@synthesize rateLabel;
@synthesize selectDate;

@synthesize titleString;
@synthesize rateString;
@synthesize dateString;
@synthesize remindIDString;
@synthesize ifAdd;

@synthesize voiceButton;
@synthesize voiceImage;
@synthesize voiceLabel;
@synthesize origianlReminder;
@synthesize voiceContainer;
@synthesize mydelegate;

@synthesize titleTextField;

int recordDuration=0;
int countDownTime=0;
NSTimer *countDowntimer;

-(void)dealloc
{
    [self.alertView removeFromSuperview];
    self.alertView.rootViewController=NULL;
    [self.recordView removeFromParentViewController];
    if(self.timer!=NULL)
        [self.timer invalidate];
    if(self.Newtimer!=NULL)
        [self.Newtimer invalidate];
    self.selectDate=NULL;
    self.titleString=NULL;
    self.dateString=NULL;
    self.rateString=NULL;
    self.remindIDString=NULL;
    self.ifAdd=NULL;
    self.isUnderRecord=NULL;
    self.origianlReminder=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.mydelegate=NULL;
    self.recordView=NULL;
    self.keyWindow=NULL;
    self.alertView=NULL;
    self.timer=NULL;
    self.Newtimer=NULL;
    self.recordPath=NULL;
    self.player=NULL;

}
-(void)viewWillAppear:(BOOL)animated
{
    recordDuration=0;
    if (titleString!=NULL){titleTextField.text=titleString;}
    if (rateString!=NULL){rateLabel.text=rateString;}
    if (dateString!=NULL)
    {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"]; //大写的 H为24小时制，小写h为12小时制
        
        NSDate *startDate= [dateFormatter dateFromString:dateString];
        
        dataPicker.date=startDate;
        
        selectDate=dateString;
        
    }
    
    //NSLog(@"%@",origianlReminder.remindTime);
    if (origianlReminder.audioUrl!=NULL)
    {
        [self showVoiceSeries];
        self.voiceLabel.text=[NSString stringWithFormat:@"%d\"",origianlReminder.autionTime];
        self.recordPath=origianlReminder.audioUrl;
        if (origianlReminder.autionTime==0){self.voiceContainer.hidden=YES;}
        else{self.voiceContainer.hidden=NO;}
    }
    
}

-(void)initSoundView
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.alertType=0;
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"添加闹钟";
    [self hidVoiceSeries];
    NSDateFormatter *nsDateFormatter = [[NSDateFormatter alloc]init];
    [nsDateFormatter setDateFormat:@"H:mm"];
    NSDate* date = dataPicker.date;
    selectDate = [nsDateFormatter stringFromDate:date];
    mydelegate=[[UIApplication sharedApplication] delegate];
    [self initDatePicker];
    [self initDataProxy];
    [self initRecordButton];
    self.alertView=[[UIWindow alloc]initWithFrame:CGRectMake(0, 0, 320, 400)];
    self.recordView=[[RecordViewController alloc]init];
    self.keyWindow = [[[UIApplication sharedApplication] delegate] window];
    [self.recordView setMotherWindow:self.alertView];
    self.alertView.rootViewController=self.recordView;
    [self.keyWindow addSubview:self.alertView];
    [self.alertView setWindowLevel:UIWindowLevelAlert];
    
    if(mydelegate.isAdmin==YES)
    {
        self.navigationItem.rightBarButtonItem=navRightButton;
        [self initNavButton];
        [self initActions];

    }
    else
    {
        self.recordButton.enabled=NO;
        self.recordButton.hidden=YES;
    }
    dataPicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
    // Do any additional setup after loading the view from its nib.
}
-(void)viewWillDisappear:(BOOL)animated{
    [titleTextField resignFirstResponder];
}
-(void)viewDidDisappear:(BOOL)animated{
    [titleTextField resignFirstResponder];
}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
    titleTextField.delegate=self;
}
-(void)initActions{
    
//    UITapGestureRecognizer *tapReconizerToSelectTitle = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setTitleAction)];
//    [self.titleView addGestureRecognizer:tapReconizerToSelectTitle];
    
    UITapGestureRecognizer *tapReconizerToSelectRate = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setRateAction)];
    [self.rateView addGestureRecognizer:tapReconizerToSelectRate];
    
}

-(void)setTitleAction{
    
    SetTextViewController *textViewController=[[SetTextViewController alloc]init];
    textViewController.tipsString=@"请输入提示";
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    textViewController.motherWindow=alertView;
    textViewController.motherLabel=self.titleLabel;
    textViewController.type=3;
    alertView.rootViewController=textViewController;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];

    
}

-(void)setRateAction{
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    SelectRateViewController *selectRate=[[SelectRateViewController alloc]init];
    [selectRate setMotherWindow:alertView];
    [selectRate setMotherLabel:rateLabel];
    alertView.rootViewController=selectRate;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
}

- (void)initNavButton {
    [navLeftButton setTarget:self];
    [navLeftButton setAction:@selector(back)];
    
    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(saveAction)];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addTitleViewTextAmendAction)];
    [self.titleView addGestureRecognizer:tapGesture];
    
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}

-(void)addTitleViewTextAmendAction{
    [self.titleTextField becomeFirstResponder];
}

-(void)amendAction{
    
    [titleTextField resignFirstResponder];

    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];

    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    Reminder *originalReminder=[self.dataManager getReminder:remindIDString];
    
    Reminder *reminder=[[Reminder alloc] init];
    reminder.reminder_id=remindIDString;
    //reminder.is_active=1;
    reminder.is_active=originalReminder.is_active;
    
    reminder.cycle=[self changeAlertCycle:rateLabel.text];
    reminder.remindTime=selectDate;
    reminder.title=titleTextField.text;
    reminder.desc=@"";
    if(self.alertType==0)
        reminder.type=originalReminder.type;
    else
        reminder.type=self.alertType;

    NSString *wavPath;
    NSString *amrPath;
    if (recordDuration>0)
    {
    reminder.audioUrl=[NSString stringWithFormat:@"/record/%@",[self.recordView getRecordFileName]];
    reminder.audioName=[self.recordView getRecordFileName];
    reminder.autionTime=recordDuration;
        
        //把wav转换成amr
        reminder.amrUrl=[NSString stringWithFormat:@"/record/%@",[self.recordView getRecordSendName]];
        reminder.amrName=[self.recordView getRecordSendName];
        wavPath=[self.recordView getRecordFilePath];
        amrPath=[self.recordView getRecordSendPath];
        if(![VoiceConverter ConvertWavToAmr:wavPath amrSavePath:amrPath]){
            [self initNavButton];
            return;
        }
    
    
    }
    else
    {
    reminder.audioUrl=originalReminder.audioUrl;
    reminder.audioName=originalReminder.audioName;
    reminder.autionTime=originalReminder.autionTime;
    }
    
    
    [self.syncManager setReminder:watchId reminder:reminder completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        
        if (result==SUCESS)
        {
            [LeoMsg showToastMsg:@"修改成功!" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            [self deleteAmrFile:amrPath];
            [self.navigationController popViewControllerAnimated:YES];
            return ;
        }
        else
        {
            [navRightButton setAction:@selector(saveAction)];
            [Tooler showHttpToast:result description:description msg:@"闹钟修改失败" parentView:self.navigationController.view  showPosition:TOAST_SHOW_END hideAfterDelay:1];
        }
    }];
    

    
    
}
-(void)saveAction{
    
    [titleTextField resignFirstResponder];
    
    [navRightButton setAction:nil];
    
    if(titleTextField.text==NULL||[titleTextField.text isEqualToString:@""])
    {
        [LeoMsg showMsg:@"闹钟标题不能为空!"];
        [self initNavButton];
        return;
    }
    
    if ([LeoMsg isTooLong:titleTextField.text ChnLength:20 EngLength:16 tipsString:@"闹钟标题" onlyUnderline:NO])
    {
        [self initNavButton];
        return;
    }

    
    if ([self.ifAdd isEqual:@"NO"])
    {
        [self amendAction];
        return ;
    }

    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
//    NSDictionary *dicNewOne = [NSDictionary dictionaryWithObjectsAndKeys:nameLabel.text,@"name",[NSString stringWithFormat:@"%d",(int)sliderBar.value],@"radius",@"还附近",@"position",@"1",@"status" , nil];
//    [myDelegate.safeDetailsDataArray addObject:dicNewOne];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;

    
    Reminder *reminder=[[Reminder alloc] init];
    reminder.is_active=1;
    reminder.cycle=[self changeAlertCycle:rateLabel.text];
    reminder.remindTime=selectDate;
    reminder.title=titleTextField.text;
    reminder.desc=@"";
    reminder.type=self.alertType;
    
    //NSString *fileName=@"/record/466853267373.caf";
    //reminder.audioUrl=fileName;
    
    reminder.audioUrl=[NSString stringWithFormat:@"/record/%@",[self.recordView getRecordFileName]];
    reminder.audioName=[self.recordView getRecordFileName];
    reminder.autionTime=recordDuration;
    //reminder.audioUrl=[self.recordView getRecordFilePath];
    
    //把wav转换成amr
    reminder.amrUrl=[NSString stringWithFormat:@"/record/%@",[self.recordView getRecordSendName]];
    reminder.amrName=[self.recordView getRecordSendName];
    NSString *wavPath=[self.recordView getRecordFilePath];
    NSString *amrPath=[self.recordView getRecordSendPath];
    if (recordDuration!=0)
    {
        if(![VoiceConverter ConvertWavToAmr:wavPath amrSavePath:amrPath]){
            [self initNavButton];
            return;
        }
        
    }
    
    [self.syncManager addReminder:watchId reminder:reminder completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        
        if (result==SUCESS)
        {
            [self.navigationController popViewControllerAnimated:YES];
             [LeoMsg showToastMsg:@"添加成功!" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            //添加成功，删除amr文件
            [self deleteAmrFile:amrPath];

        }
        else
        {
            [Tooler showHttpToast:result description:description msg:@"添加闹钟失败" parentView:self.navigationController.view  showPosition:TOAST_SHOW_END hideAfterDelay:1];
            [self initNavButton];
        }
    }];

    
    
    
}

-(void)deleteAmrFile:(NSString *)file_url
{

    if(file_url==NULL)
    {
        NSLog(@"deleteAmrFile,file_url is null.");
        return;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err=nil;
    [fileManager removeItemAtPath:file_url error:&err];
    if(err!=nil)
    {
        NSLog(@"deleteAmrFile,delete file error,error is %@.",err);
    }
}
-(void)canNotChanged
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"]; //大写的 H为24小时制，小写h为12小时制
    
    NSDate *startDate= [dateFormatter dateFromString:dateString];
    
    dataPicker.date=startDate;
}
- (void)initDatePicker{
    dataPicker.datePickerMode = UIDatePickerModeTime;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if(myDelegate.isAdmin==NO)
    {
        [dataPicker addTarget:self action:@selector(canNotChanged) forControlEvents:UIControlEventValueChanged];
 
    }
    else
       {
           [dataPicker addTarget:self action:@selector(dataChanged:) forControlEvents:UIControlEventValueChanged];
       }
}

- (void)dataChanged:(id)sender{
    NSDateFormatter *nsDateFormatter = [[NSDateFormatter alloc]init];
    [nsDateFormatter setDateFormat:@"H:mm"];
    UIDatePicker *control = (UIDatePicker*)sender;
    NSDate* date = control.date;
    selectDate = [nsDateFormatter stringFromDate:date];
    NSLog(@"%@",selectDate);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(NSString *)changeAlertCycle:(NSString *)cycle
{
    NSString *newCycle=@"";
    
    if ([cycle isEqualToString:@"每天"]){return @"1,2,3,4,5,6,7";}
    
    for (int i=0;i<cycle.length;i=i+3)
    {
        NSRange range = NSMakeRange(i, 2);
        NSString *subString = [cycle substringWithRange:range];
        
        if ([subString isEqual:@"周一"]){newCycle=[newCycle stringByAppendingString:@"1,"];}
        if ([subString isEqual:@"周二"]){newCycle=[newCycle stringByAppendingString:@"2,"];}
        if ([subString isEqual:@"周三"]){newCycle=[newCycle stringByAppendingString:@"3,"];}
        if ([subString isEqual:@"周四"]){newCycle=[newCycle stringByAppendingString:@"4,"];}
        if ([subString isEqual:@"周五"]){newCycle=[newCycle stringByAppendingString:@"5,"];}
        if ([subString isEqual:@"周六"]){newCycle=[newCycle stringByAppendingString:@"6,"];}
        if ([subString isEqual:@"周日"]){newCycle=[newCycle stringByAppendingString:@"7,"];}
        
    }
    if ([newCycle isEqualToString:@""])
    {
        return newCycle;
    }
    else
    {
        NSRange range = NSMakeRange(0, newCycle.length-1);
        newCycle = [newCycle substringWithRange:range];
        return newCycle;
    }
}


-(void)initRecordButton
{
    voiceImage.image=[UIImage imageNamed:@"chat_w.png"];
    NSLog(@"又来录音111");


    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(startPress:)];
    [self.recordButton addGestureRecognizer:longPress];
    self.isAdd=NO;
    self.isCancle=NO;
    [self initVoiceAction];

    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (IBAction)startPress:(UISwipeGestureRecognizer *)sender
{
    [self.voiceButton.imageView stopAnimating];
    self.voiceButton.imageView.animationImages=NULL;
    //取消定时器
    if (countDowntimer!=nil){
        [countDowntimer invalidate];
        self.voiceLabel.text=[NSString stringWithFormat:@"%d\"",[self.recordView getDuration]];
        countDowntimer = nil;
        self.alertView.hidden=YES;
    }
    
    
    
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:
            [self startRecord];
            self.previous = [sender locationInView:self.view];
            self.isUnderRecord = YES;
            //self.startRecordDate=[NSDate date];
            break;
        case UIGestureRecognizerStateEnded:
            self.isUnderRecord = NO;
            if(!self.isCancle)
            {
                [self stopRecord];
            }
            else
            {
                [self cancleRecord];
            }
            break;
            
        default:
            if(self.isUnderRecord){
                self.current = [sender locationInView:self.view];
                if(self.previous.y -self.current.y>50)
                {
                    [self preCancleRecord];
                    self.recordView.isCancle=YES;
                    self.previous = self.current;
                }
            }
//            NSTimeInterval recordTime=[[NSDate date] timeIntervalSinceDate:self.startRecordDate];//
//            long long dTime = [[NSNumber numberWithDouble:recordTime] longLongValue]; // 将double转为long long型
//            if ((dTime>19)&&(dTime<10000)){self.alertView.hidden=YES;}
//
            break;
    }
    
    
}
-(void)startRecord
{
    NSLog(@"又来录音2222");
    self.isCancle=NO;
    if(!self.isAdd)
    {
        self.recordView.infoLable.text=@"手指上滑，取消发送";
        self.recordView.actionImg.image=[UIImage imageNamed:@"record_anim0@2x"];

        self.isAdd=YES;
        [self.alertView makeKeyAndVisible];
        [self.recordView start];
        
        self.recordView.actionImg.animationImages=[NSArray arrayWithObjects:
                                                   [UIImage imageNamed:@"record_anim0@2x.png"],
                                                   [UIImage imageNamed:@"record_anim1@2x.png"],
                                                   [UIImage imageNamed:@"record_anim2@2x.png"],                                                   [UIImage imageNamed:@"record_anim3@2x.png"],                                                   [UIImage imageNamed:@"record_anim4@2x.png"],                                                   [UIImage imageNamed:@"record_anim5@2x.png"],                                                   [UIImage imageNamed:@"record_anim6@2x.png"],                                                   [UIImage imageNamed:@"record_anim7@2x.png"],                                                   [UIImage imageNamed:@"record_anim8@2x.png"],                                                   [UIImage imageNamed:@"record_anim9@2x.png"],                                                   [UIImage imageNamed:@"record_anim10@2x.png"],nil];
        [self.recordView.actionImg setAnimationDuration:1.0f];
        [self.recordView.actionImg startAnimating];
        
        countDownTime=20;
        [self.Newtimer invalidate];
        self.Newtimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeUp) userInfo:nil repeats:YES];
        [self.Newtimer setFireDate:[NSDate distantPast]];


    }
    
}

- (void)stopRecord {
    NSLog(@"又来录音3333");

    self.isCancle=NO;
    self.isAdd=NO;
    //录制时间太短
    if([self.recordView getDuration]<1)
    {
        [self.recordView stop];
        self.recordView.infoLable.text=@"录音时间太短";
        self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
        return;
    }
    [self.recordView stop];
    self.alertView.hidden=YES;
    NSString *file_url=[self.recordView getRecordFilePath];
    if(file_url==NULL)
    {
        NSLog(@"%@,stopRecord,file_url is null.",record_tag);
        return;
    }
    
    self.voiceLabel.text=[NSString stringWithFormat:@"%d\"",[self.recordView getDuration]];
    self.recordPath=[NSString stringWithFormat:@"/record/%@",[self.recordView getRecordFileName]];
    recordDuration=[self.recordView getDuration];
    [self showVoiceSeries];
    NSLog(@"%@路径",[self.recordView getRecordFilePath]);
    
    self.voiceContainer.hidden=NO;
    self.alertType=1;

    
}
-(void)timeUp
{
    countDownTime--;
    if (countDownTime==0){
        self.alertView.hidden=YES;
    }
}
-(void)timeDown
{
    self.alertView.hidden=YES;
    [self.timer invalidate];
}
-(void)preSendRecord
{
    self.isCancle=NO;
    self.recordView.infoLable.text=@"手指上滑，取消发送";
    UIImage *sendImg=[UIImage imageNamed:@"record_anim0@2x"];
    self.recordView.actionImg.image=sendImg;
    sendImg=NULL;
    [self.recordView.actionImg startAnimating];
}
- (void)preCancleRecord {
    [self.recordView.actionImg stopAnimating];
    self.isCancle=YES;
    self.recordView.infoLable.text=@"松开手指，取消发送";
    UIImage *cancleImg=[UIImage imageNamed:@"record_Trash@2x"];
    self.recordView.actionImg.image=cancleImg;
    cancleImg=NULL;
}
- (void)cancleRecord {
    self.alertView.hidden=YES;
    self.isAdd=NO;
    self.isCancle=NO;
    [self.recordView stop];
    NSString *file_url=[self.recordView getRecordFilePath];
    if(file_url==NULL)
    {
        NSLog(@"%@,stopRecord,file_url is null.",record_tag);
        return;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err=nil;
    [fileManager removeItemAtPath:file_url error:&err];
    if(err!=nil)
    {
        //NSLog(@"%@,cancleRecord,delete file error,error is %@.",chat_tag,err);
    }
}
//播放语音模块
-(void)initVoiceAction
{
    NSLog(@"AAction123!");

    self.is_play=NO;
    UITapGestureRecognizer *tapAudio = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playAction)];
    //tap.delegate=self;
    [self.voiceContainer addGestureRecognizer:tapAudio];
    [self.voiceButton addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchDown];
}
-(void)changeVoiceLabelAction{
    NSString *voiceNum=self.voiceLabel.text;
    voiceNum=[voiceNum substringWithRange:NSMakeRange(0,1)];
    int k=[voiceNum intValue]-1;
    if (k<0){
        //取消定时器
        [countDowntimer invalidate];
        countDowntimer = nil;
        //k=[self.recordView getDuration];
        self.voiceLabel.text=[NSString stringWithFormat:@"%d\"",recordDuration];
        return;
    }
    self.voiceLabel.text=[NSString stringWithFormat:@"%d\"",k];

}
-(void)countDownAction{
    recordDuration=[self.voiceLabel.text intValue];
    countDowntimer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeVoiceLabelAction) userInfo:nil repeats:YES];
    [countDowntimer setFireDate:[NSDate distantPast]];
}
-(void)playAction
{
    NSLog(@"AAction!");
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    
    if(!self.is_play)
    {
        self.voiceButton.imageView.animationImages=[NSArray arrayWithObjects:
                                                 [UIImage imageNamed:@"voice_w_anim1@2x.png"],
                                                 [UIImage imageNamed:@"voice_w_anim2@2x.png"],
                                                 [UIImage imageNamed:@"voice_w_anim3@2x.png"],                                           nil];
        [self.voiceButton.imageView setAnimationDuration:2.0f];
        [self.voiceButton.imageView startAnimating];
        [self countDownAction];
        [self play:self.recordPath];
        self.is_play=YES;
    }
    else
    {
        [self.player stop];
        [self.voiceButton.imageView stopAnimating];
        self.voiceButton.imageView.animationImages=NULL;
        self.is_play=NO;
    }
    
}
-(void)play:(NSString *)path
{
    if(path==NULL)
    {
        NSLog(@"%@,play,path is null.",send_tag);
        return;
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    path=[documentsDirectory stringByAppendingString:path];
    NSLog(@"%@,play,path is %@.",send_tag,path);
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:path];
    if(find)
    {
        AVAudioSession *audioSession=[AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [audioSession setActive:YES error:nil];
        NSError *error=nil;
        self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:path] error:&error];
        if(error!=nil)
        {
            NSLog(@"%@,playRecord,create player error,error is %@.",send_tag,error);
            return;
        }
        self.player.delegate=self;
        self.player.numberOfLoops=0;
        self.player.volume=1.0;
        [self.player prepareToPlay];
        [self.player play];
    }
    else
    {
        NSLog(@"%@,playRecord,the record file is not exist.",send_tag);
    }
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self stop];
}
-(void)stop
{
    if(self.player!=NULL)
    {
        [self.player stop];
        [self.voiceButton.imageView stopAnimating];
        self.voiceButton.imageView.animationImages=NULL;
    }
    self.is_play=NO;
}
//隐藏声音图片
-(void)hidVoiceSeries
{
    self.voiceButton.hidden=YES;
    self.voiceImage.hidden=YES;
    self.voiceLabel.hidden=YES;
    
}
-(void)showVoiceSeries
{
    self.voiceButton.hidden=NO;
    self.voiceImage.hidden=NO;
    self.voiceLabel.hidden=NO;

}


//***键盘遮挡部分
//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGFloat kbHeight =300;
    int INTERVAL_KEYBOARD=258;
    
    //t offset = frame.origin.y + 32 - (self.view.frame.size.height - 500);//键盘高度300
    CGFloat offset = (textField.frame.origin.y+textField.frame.size.height+INTERVAL_KEYBOARD) - (self.view.frame.size.height - kbHeight);
    
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    NSLog(@"%d",offset);
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}
//点击空白取消编辑
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [titleTextField resignFirstResponder];
}
- (IBAction)passTextFieldChange:(id)sender {

    NSString* testString=self.titleTextField.text;
    BOOL hasEng=NO; BOOL hasChn=NO;
    for (int i = 0; i<testString.length; i++) {
        char commitChar = [testString characterAtIndex:i];
        NSString *temp = [testString substringWithRange:NSMakeRange(i,1)];
        //异常情况，不允许第一个字符空
        if (([temp isEqual:@" "])&&(testString.length==1)){
            self.titleTextField.text=@"";
            return;
        }
        const char *u8Temp = [temp UTF8String];
        if (u8Temp!=NULL&&3==strlen(u8Temp)){
            hasChn=YES;//NSLog(@"字符串中含有中文");
        }else if((commitChar>64)&&(commitChar<123)){
            hasEng=YES;//NSLog(@"字符串中含有英文字母");
        }else if((commitChar>47)&&(commitChar<58)){
            hasEng=YES;//NSLog(@"字符串中含有数字");
        }else{
            NSLog(@"字符串中含有非法字符");
            if ([temp isEqualToString:@" "]){}else{
            if (![temp isEqualToString:@"_"]){
                
                    [LeoMsg showMsg:[NSString stringWithFormat:@"%@为非法字符,请重新输入",[testString substringWithRange:NSMakeRange(testString.length-1,1)]]];
                if (testString.length>=1){
                    self.titleTextField.text=[testString substringToIndex:testString.length-1];}
                
                return ;}
            }
        }

    }
    if ((!hasChn)){
        if ([LeoMsg convertToInt:testString]>16){
           self.titleTextField.text=[testString substringToIndex:16];
            [LeoMsg showMsg:@"闹钟标题太长,中文字符只能输入8个,英文字符只能输入20个"];
            return;

        }
    }else if ([LeoMsg convertToInt:testString]>20){
        self.titleTextField.text=[testString substringToIndex:10];
        [LeoMsg showMsg:@"闹钟标题太长,中文字符只能输入8个,英文字符只能输入20个"];
        return;

    }
    
}



@end
